#include "formtableviewer.h"
#include "ui_formtableviewer.h"
#include <QDebug>

FormTableViewer::FormTableViewer(HousingDBMS *p_dbms, QWidget *parent) :
    QWidget(parent),
    mp_dbms(p_dbms),
    ui(new Ui::FormTableViewer)
{
    ui->setupUi(this);
}

FormTableViewer::~FormTableViewer()
{
    delete ui;
}

void FormTableViewer::on_btnLoad_clicked()
{
    int db_index = ui->combo_tables->currentIndex();
    if(db_index <0) return;
    ui->tableWidget->clear();
    ui->tableWidget->setRowCount(0);
    ui->tableWidget->setColumnCount(0);
    QVariantList qv_pkeys_lst;
    QStringList fld_names = mp_dbms->get_db_fld_names(db_index);
    SLEE_HDB_REC_LST qh_data_lst;
    qh_data_lst = mp_dbms->get_db_data(db_index, qv_pkeys_lst);
    QTableWidgetItem *mp_item = new QTableWidgetItem;
    ui->tableWidget->setColumnCount(fld_names.size()+1);
    mp_item->setText("pkey");
    ui->tableWidget->setHorizontalHeaderItem(0,mp_item);
    for(int i = 0; i<fld_names.size(); i++)
    {
        mp_item = new QTableWidgetItem;
        mp_item->setText(fld_names.at(i));
        ui->tableWidget->setHorizontalHeaderItem(i+1,mp_item);
    }
    for(int i = 0; i<qh_data_lst.size(); i++)
    {
        ui->tableWidget->insertRow(i);
        mp_item = new QTableWidgetItem;
        mp_item->setText(qv_pkeys_lst.at(i).toString());
        ui->tableWidget->setItem(i,0,mp_item);
        for(int j = 0; j<fld_names.size(); j++)
        {
            mp_item = new QTableWidgetItem;
            mp_item->setText(qh_data_lst.at(i).value(j).toString());
            ui->tableWidget->setItem(i,j+1,mp_item);
        }

    }
}

void FormTableViewer::load_db_list()
{
    if(mp_dbms == NULL) return;
    ui->combo_tables->clear();
    ui->combo_tables->addItems(mp_dbms->get_db_names());

}
